package com.hu.system.service.impl;

import java.util.List;
import java.util.ArrayList;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.github.pagehelper.PageHelper;
import com.hu.common.utils.SecurityUtils;
import com.hu.system.mapper.StockDetailMapper;
import com.hu.system.mapper.SysUserShopMapper;
import com.hu.system.domain.StockDetail;
import com.hu.system.service.IStockDetailService;

/**
 * 库存明细统计Service业务层处理
 *
 * @author hu
 * @date 2025-01-21
 */
@Service
public class StockDetailServiceImpl implements IStockDetailService {
    @Autowired
    private StockDetailMapper stockDetailMapper;

    @Autowired
    private SysUserShopMapper userShopMapper;

    /**
     * 查询库存明细统计列表
     *
     * @param stockDetail 库存明细查询条件
     * @return 库存明细统计列表
     */
    @Override
    public List<StockDetail> selectStockDetailList(StockDetail stockDetail) {
        Long userId = SecurityUtils.getUserId();

        // 管理员查看全部
        if (userId != null && userId == 1L) {
            return stockDetailMapper.selectStockDetailList(stockDetail);
        }

        // 普通用户根据店铺过滤
        // 保存分页参数
        com.github.pagehelper.Page<?> originalPage = com.github.pagehelper.PageHelper.getLocalPage();
        Integer originalPageNum = originalPage != null ? originalPage.getPageNum() : null;
        Integer originalPageSize = originalPage != null ? originalPage.getPageSize() : null;

        // 清除分页参数避免影响店铺查询
        PageHelper.clearPage();
        List<Long> shopIds = userShopMapper.selectShopIdsByUserId(userId);

        // 恢复分页参数
        if (originalPageNum != null && originalPageSize != null) {
            PageHelper.startPage(originalPageNum, originalPageSize);
        }

        if (shopIds == null || shopIds.isEmpty()) {
            return new ArrayList<>();
        }

        // 设置店铺ID过滤条件（支持多店铺）
        stockDetail.getParams().put("shopIdList", shopIds);

        return stockDetailMapper.selectStockDetailList(stockDetail);
    }
}

